<?php

namespace app\api\controller\worker;

use app\api\controller\Base;
use app\common\model\AdminModel;
use app\common\model\node\NodeProcessModel;
use app\common\model\RoleAuthModel;
use app\common\model\RoleModel;
use app\common\model\worker\CustomerAuthModel;
use app\common\model\worker\CustomerBudgetModel;
use app\common\model\worker\CustomerContractModel;
use app\common\model\worker\CustomerGoodsDataModel;
use app\common\model\worker\CustomerModel;
use app\common\model\worker\CustomerRectifyDataModel;
use app\common\model\worker\CustomerRectifyModel;
use app\common\model\worker\CustomerRulerModel;
use app\common\model\worker\OrderInstallLog;
use app\common\model\worker\OrderModel;
use app\common\model\worker\RecommendModel;
use app\common\model\worker\TaskModel;
use think\Request;
use helper\Utils;
use think\facade\Db;
class OrderController extends Base
{

    private $model;
    private $taskModel;

    /**
     * 构造方法
     * @access public
     * @throws \Exception
     */
    public function __construct()
    {
        parent::__construct();
        $this->checkLogin();
        $this->model = new OrderModel();
        $this->taskModel = new TaskModel();
    }

    /**
     * 订单列表
     */
    public function index()
    {
        $pageSize = $this->request->param('pageSize/d', 20); //每页多少条
        $pageNumber = $this->request->param('pageNumber/d'); //当前页
        $sortName = $this->request->param('sortName'); //排序字段
        $sortOrder = $this->request->param('sortOrder', 'desc'); //升序降序
        $order = !empty($sortName) ? "{$sortName} {$sortOrder}" : ''; //排序
        $keyword = $this->request->param('keyword');
        $map = [];
        if (!empty($keyword)) {
            $field = $this->request->param('field/s', 'name');
            if ($field == 'name') $map[] = ['name', 'like', '%' . $keyword . '%'];
            if ($field == 'mobile') $map[] = ['mobile', 'like', '%' . $keyword . '%'];
        }
        $searchData = $this->getSearchData();
        $data = ['total' => 0, 'rows' => []];
        $data['total'] = $this->model->withSearch('filter', $searchData)->count();
        if ($data['total'] > 0) {
            $rows = $this->model->withSearch('filter', $searchData)->page($pageNumber, $pageSize)
                ->where($map)
                ->order($order)->select()->toArray();
            $rows = $this->model->_formatList100($rows);
            $data['rows'] = $rows;
        }
        $this->result($data);
    }

    /**
     * 添加订单--下单
     */
    public function add(Request $request)
    {

        $param = $request->param();
        $order_type = $param['order_type'] ?? 0;
        $type = $param['type'] ?? 0;//0 正单 1美容 2 安装 3补材料
        if (!in_array($order_type, [0, 1, 3, 4, 5, 6, 7, 8, 9])) {
            $this->result([], "订单类型参数不正确", 0);
        }
        $data = [];
        Db::startTrans();
        if ($order_type == 0) {

            $rule['customer_id|客户ID'] = 'require';
            $rule['goods_data_id|产品id'] = 'require';
            $rule['install_notices|安装注意事项'] = 'require';
            $orderInfo = $this->model->where('customer_id',$param['customer_id'])->where('goods_data_id',$param['goods_data_id'])->find();
            if($orderInfo){
                exception('该客户商品已下单，请勿重复下单');
            }
            $customerGoodsData = CustomerGoodsDataModel::where('id',$param['goods_data_id'])->find();
            if($type == 0){//正单
                $rule['cad_imgs|cad图纸' ] = 'require';
                $designer_id = CustomerRulerModel::where('id',$customerGoodsData['ruler_id'])->value('admin_id');
                if($this->loginInfo['id'] !=$designer_id) exception('下单设计师不符合');

                $node_id = 16;
            }elseif($type == 1){//美容
                $rule['rectify_content|验收明细'] = 'require';
                $budget_id = CustomerBudgetModel::where('id',$customerGoodsData['budget_id'])->value('admin_id');
                if($this->loginInfo['id'] !=$budget_id) exception('下单客户代表不符合');
                $node_id = 20;
            }elseif($type == 2){//安装
                $rule['rectify_content|验收明细'] = 'require';
                $budget_id = CustomerBudgetModel::where('id',$customerGoodsData['budget_id'])->value('admin_id');
                if($this->loginInfo['id'] !=$budget_id) exception('下单客户代表不符合');
                $node_id = 21;

            }elseif($type == 3){//补材料

                $designer_id = CustomerRulerModel::where('id',$customerGoodsData['ruler_id'])->value('admin_id');
                if($this->loginInfo['id'] !=$designer_id) exception('下单设计师不符合');
                $node_id = 19;

            }
            //开始校验
            $this->validate($param, $rule);
            if($type == 1 || $type == 2){
                $result = CustomerGoodsDataModel::where('id',$param['goods_data_id'])->update(['rectify_content'=>json_encode($param['rectify_content'])]);
                if (!$result) {
                    // 回滚事务
                    Db::rollback();
                    $this->result([], "操作失败", 0);
                }
            }

            $data['customer_id'] = $param['customer_id'];
            $data['goods_data_id'] = $param['goods_data_id'];
            $data['order_sn']  = Utils::builderOrderSn();
            $data['action_admin_id'] = $this->loginInfo['id'];//操作人id
            if (isset($param['cad_imgs']) && !empty($param['cad_imgs'])) {
                $data['cad_imgs'] = json_encode($param['cad_imgs'], JSON_UNESCAPED_UNICODE);
            }
            //总费用
            if(isset($param['total_amount']) && $param['total_amount']){
                $data['total_amount'] = $param['total_amount'];
            }
            $data['install_notices'] = json_encode($param['install_notices'], JSON_UNESCAPED_UNICODE);
            $nodeProcess = NodeProcessModel::where('node_id', $node_id)->order('id', 'asc')->find();
            //补材料为客户代表
            if($type == 3){
                $customerGoodsData = CustomerGoodsDataModel::where('id',$param['goods_data_id'])->find();
                $budget_id = CustomerBudgetModel::where('id',$customerGoodsData['budget_id'])->value('admin_id');
                $nodeProcess['audit_admin_id'] = $budget_id;
            }
            $order_id = $this->model->insert($data, true);
            if (!$order_id) {
                // 回滚事务
                Db::rollback();
                $this->result([], "操作失败", 0);
            }

            $dataTask = [
                'customer_id' => $param['customer_id'],
                'order_id' => 0,
                'node_id' => $node_id,
                'process_id' => $nodeProcess['id'],
                'receive_admin_id' => $nodeProcess['audit_admin_id'],
                'action_table_id' => $order_id,//操作表id
                'admin_id' => $this->loginInfo['id']
            ];

            $result = $this->taskModel->commonAddTask($dataTask);
            if (!$result) {
                // 回滚事务
                Db::rollback();
                $this->result([], "操作失败", 0);
            }

            $up_data = ['order_status' => 0.1, 'order_id' => $order_id];//采购审核中-客户代表审核中
        } elseif ($order_type == 1 && $type ==0) {
            $rule['id|订单id'] = 'require';
            $rule['goods_data_id|产品id'] = 'require';
            $rule['back_files|工厂回传文件'] = 'require';
            //开始校验
            $this->validate($param, $rule);

            $customerGoodsData = CustomerGoodsDataModel::where('id',$param['goods_data_id'])->find();
            $designer_id = CustomerRulerModel::where('id',$customerGoodsData['ruler_id'])->value('admin_id');


            $data['back_files'] = json_encode($param['back_files'], JSON_UNESCAPED_UNICODE);
            $nodeProcess = NodeProcessModel::where('node_id', 17)->order('id', 'asc')->find();

            $dataTask = [
                'customer_id' => $param['customer_id'],
                'order_id' => $param['id'],
                'node_id' => 17,
                'process_id' => $nodeProcess['id'],
                'receive_admin_id' => $designer_id,//指定设计师接受
                'action_table_id' => $param['id'],//操作表id
                'admin_id' => $this->loginInfo['id']
            ];

            $result = $this->taskModel->commonAddTask($dataTask);
            if (!$result) {
                // 回滚事务
                Db::rollback();
                $this->result([], "操作失败", 0);
            }
            $up_data = ['order_status' => 2];//拆单完成

        }
//        elseif($type == 2){
//            $this->result([], "操作失败,只有查看权限", 0);
//        }
        elseif ($order_type == 3 && ($type == 0  || $type == 3)) { //财务核算，只有正单和补材料

            $rule['id|订单id'] = 'require';
            $rule['goods_data_id|产品id'] = 'require';
            $rule['cost_files|工厂成本文件'] = 'require';
            $rule['wage_infos|工本费/其他费用'] = 'require';
            //$rule['gross_profit|毛利/合计金额'] = 'require';

            //开始校验
            $this->validate($param, $rule);
            //是否有差异
            if(isset($param['is_diff']) && $param['is_diff']){
                $data['is_diff'] = $param['is_diff'];
            }
            //差异内容
            if(isset($param['diff_content']) && $param['diff_content']){
                $data['diff_content'] = json_encode($param['diff_content'], JSON_UNESCAPED_UNICODE);
            }
            //返利信息
            if(isset($param['rebate_infos']) && $param['rebate_infos']){
                $data['rebate_infos'] = $param['rebate_infos'];
            }

            $data['wage_infos'] = json_encode($param['wage_infos'], JSON_UNESCAPED_UNICODE);
            $data['cost_files'] = json_encode($param['cost_files'], JSON_UNESCAPED_UNICODE);
            //返利
            if(isset($param['rebate_infos']) && $param['rebate_infos']){
                $data['rebate_infos'] = json_encode($param['rebate_infos'], JSON_UNESCAPED_UNICODE);
            }
            //毛利
            if(isset($param['gross_profit']) && $param['gross_profit']){
                $data['gross_profit'] = $param['gross_profit'];
            }

            $nodeProcess = NodeProcessModel::where('node_id', 18)->order('id', 'asc')->find();

            $dataTask = [
                'customer_id' => $param['customer_id'],
                'order_id' => $param['id'],
                'node_id' => 18,
                'process_id' => $nodeProcess['id'],
                'receive_admin_id' => $nodeProcess['audit_admin_id'],
                'action_table_id' => $param['id'],//操作表id
                'admin_id' => $this->loginInfo['id']
            ];


            $result = $this->taskModel->commonAddTask($dataTask);
            if (!$result) {
                // 回滚事务
                Db::rollback();
                $this->result([], "操作失败", 0);
            }
            $up_data = ['order_status' => 3.1];//提交完，会计审核中
        } elseif ($order_type == 4) {
            $rule['id|订单id'] = 'require';
            $rule['goods_data_id|产品id'] = 'require';
            $rule['arrival_time|到货日期'] = 'require';
            //开始校验
            $this->validate($param, $rule);
            $data['arrival_time'] = $param['arrival_time'];
            $up_data = ['order_status' => 5];
        } elseif ($order_type == 5) {
            $rule['id|订单id'] = 'require';
            $rule['goods_data_id|产品id'] = 'require';
            //开始校验
            $this->validate($param, $rule);
            if (isset($param['install_time']) && !empty($param['install_time'])) {
                $customerGoodsData = CustomerGoodsDataModel::where('id',$param['goods_data_id'])->find();
                $budget_id = CustomerBudgetModel::where('id',$customerGoodsData['budget_id'])->value('admin_id');
                if($this->loginInfo['id'] !=$budget_id) exception('客户代表不符合');

                $data['install_time'] = $param['install_time'];
                $up_data = ['order_status' => 6];
            }
            //填写安排安装转入待安装
            if (isset($param['install_admin_id']) && !empty($param['install_admin_id'])) {
                $customerGoodsData = CustomerGoodsDataModel::where('id',$param['goods_data_id'])->find();
                $budget_id = CustomerBudgetModel::where('id',$customerGoodsData['budget_id'])->value('admin_id');
                if($this->loginInfo['id'] !=$budget_id) exception('客户代表不符合');

                $data['install_admin_id'] = $param['install_admin_id'];
                $up_data = ['order_status' => 6];
            }
            if (isset($param['arrival_time']) && !empty($param['arrival_time'])) {
                $data['arrival_time'] = $param['arrival_time'];
            }
        } elseif ($order_type == 6) {
            $rule['id|订单id'] = 'require';
            $rule['goods_data_id|产品id'] = 'require';
            //开始校验
            $this->validate($param, $rule);
            //开始安装转入安装中
            if (isset($param['is_read']) && !empty($param['is_read'])) {
                $install_admin_id = OrderModel::where('id',$param['id'])->value('install_admin_id');
                if($this->loginInfo['id'] != $install_admin_id) exception('安装工不符合');
                $data['is_read'] = $param['is_read'];
                $up_data = ['order_status' => 7];
            }
            if (isset($param['upload_imgs']) && !empty($param['upload_imgs'])) {
                $data['upload_imgs'] = json_encode($param['upload_imgs'], JSON_UNESCAPED_UNICODE);
                $up_data = ['order_status' => 7];
            }
            //调整送货日期
            if (isset($param['arrival_time']) && !empty($param['arrival_time'])) {
                $data['arrival_time'] = $param['arrival_time'];
            }
            //调整安装日期
            if (isset($param['install_time']) && !empty($param['install_time'])) {
                $customerGoodsData = CustomerGoodsDataModel::where('id',$param['goods_data_id'])->find();
                $budget_id = CustomerBudgetModel::where('id',$customerGoodsData['budget_id'])->value('admin_id');
                if($this->loginInfo['id'] !=$budget_id) exception('客户代表不符合');
                $data['install_time'] = $param['install_time'];
            }
            //调整安装工
            if (isset($param['install_admin_id']) && !empty($param['install_admin_id'])) {
                $customerGoodsData = CustomerGoodsDataModel::where('id',$param['goods_data_id'])->find();
                $budget_id = CustomerBudgetModel::where('id',$customerGoodsData['budget_id'])->value('admin_id');
                if($this->loginInfo['id'] !=$budget_id) exception('客户代表不符合');
                $data['install_admin_id'] = $param['install_admin_id'];
            }
        } elseif ($order_type == 7) {
            $rule['id|订单id'] = 'require';
            $rule['goods_data_id|产品id'] = 'require';
            //开始校验
            $this->validate($param, $rule);

            $install_admin_id = OrderModel::where('id',$param['id'])->value('install_admin_id');
            if($this->loginInfo['id'] != $install_admin_id) exception('安装工不符合');

            //安装日志
            $data_log = [];
            if (isset($param['today_install_imgs']) && !empty($param['today_install_imgs'])) {
                $data_log['today_install_imgs'] = json_encode($param['today_install_imgs'], JSON_UNESCAPED_UNICODE);
                $data_log['order_id'] = $param['id'];
            }
            if (isset($param['today_close_imgs']) && !empty($param['today_close_imgs'])) {
                $data_log['today_close_imgs'] = json_encode($param['today_close_imgs'], JSON_UNESCAPED_UNICODE);
                $data_log['order_id'] = $param['id'];
            }
            if (isset($param['remain_day']) && !empty($param['remain_day'])) {
                $data_log['remain_day'] = $param['remain_day'];
                $data_log['order_id'] = $param['id'];
            }
            if ($data_log) {

                $result = OrderInstallLog::insert($data_log);
                if (!$result) {
                    // 回滚事务
                    Db::rollback();
                    $this->result([], "操作失败", 0);
                }
            }
            //安装工填写 完成安装 转入待验收
            if (isset($param['is_legacy']) && !empty($param['is_legacy'])) {
                $data['is_legacy'] = $param['is_legacy'];
                $up_data = ['order_status' => 8];
            }
            if (isset($param['legacy_infos']) && !empty($param['legacy_infos'])) {
                $data['legacy_infos'] = json_encode($param['legacy_infos'], JSON_UNESCAPED_UNICODE);//
                $up_data = ['order_status' => 8];
            }
            if (isset($param['finish_install_imgs']) && !empty($param['finish_install_imgs'])) {
                $data['finish_install_imgs'] = json_encode($param['finish_install_imgs'], JSON_UNESCAPED_UNICODE);
                $up_data = ['order_status' => 8];
            }
            if (isset($param['finish_close_imgs']) && !empty($param['finish_close_imgs'])) {
                $data['finish_close_imgs'] = json_encode($param['finish_close_imgs'], JSON_UNESCAPED_UNICODE);
                $up_data = ['order_status' => 8];
            }
            if (isset($param['finish_install_time']) && !empty($param['finish_install_time'])) {
                $data['finish_install_time'] = $param['finish_install_time'];
                $up_data = ['order_status' => 8];
            }
            if (isset($param['finish_day']) && !empty($param['finish_day'])) {
                $data['finish_day'] = $param['finish_day'];
                $up_data = ['order_status' => 8];
            }



        }elseif($order_type == 8) {
            $rule['id|订单id'] = 'require';
            $rule['goods_data_id|产品id'] = 'require';
            $rule['customer_id|客户id'] = 'require';
            $rule['is_rectify|是否整改有问题'] = 'require';
            //开始校验
            $this->validate($param, $rule);
            $orderInfo = OrderModel::where('id',$param['id'])->find();
            $customerGoodsData = CustomerGoodsDataModel::where('id',$orderInfo['goods_data_id'])->find();
            $data['is_rectify'] = $param['is_rectify'];
            $up_data = ['order_status' => 9];//默认进入下一步
            $problem_types = [];
            if (isset($param['rectify_content']) && !empty($param['rectify_content'])) {
                $data['rectify_content'] = json_encode($param['rectify_content'], JSON_UNESCAPED_UNICODE);
                foreach ($param['rectify_content'] as $v) {

                    if (in_array($v['type'], [1, 2, 3])) {
                        $problem_types[] = $v['type'];

                        $up_data = ['order_status' => 8.1];
                    }
                    if ($v['type'] == 1) {
                        $type_rectify_content[1][] = ['question_way' => $v['question_way'], 'group_name' => $v['group_name'], 'file_url' => $v['file_url']];
                    } elseif ($v['type'] == 2) {
                        $type_rectify_content[2][] = ['question_way' => $v['question_way'], 'group_name' => $v['group_name'], 'file_url' => $v['file_url']];
                    } elseif ($v['type'] == 3) {
                        $type_rectify_content[3][] = ['question_way' => $v['question_way'], 'group_name' => $v['group_name'], 'file_url' => $v['file_url']];
                    }
                }

                if ($problem_types) {
                    $problem_types = array_unique($problem_types);
                    foreach ($problem_types as $k => $v) {
                        $customerRectifyData[$k]['type'] = $v;
                        $customerRectifyData[$k]['goods_id'] = $customerGoodsData['goods_id'];
                        $customerRectifyData[$k]['goods_name'] = $customerGoodsData['goods_name'];
                        $customerRectifyData[$k]['customer_id'] = $param['customer_id'];
                        $customerRectifyData[$k]['rectify_content'] = json_encode($type_rectify_content[$v]);
                        $customerRectifyData[$k]['action_admin_id'] = $this->loginInfo['id'];
                        $customerRectifyData[$k]['status'] = 1;
                        $customerRectifyData[$k]['budget_id'] = $customerGoodsData['budget_id'];
                        $customerRectifyData[$k]['budget_detail_id'] = $customerGoodsData['budget_detail_id'];
                        $customerRectifyData[$k]['budget_status'] = $customerGoodsData['budget_status'];
                        $customerRectifyData[$k]['ruler_id'] = $customerGoodsData['ruler_id'];
                        $customerRectifyData[$k]['ruler_detail_id'] =$customerGoodsData['ruler_detail_id'];
                        $customerRectifyData[$k]['design_status'] = $customerGoodsData['design_status'];
                        $customerRectifyData[$k]['draw_id'] = $customerGoodsData['draw_id'];
                        $customerRectifyData[$k]['order_status'] = 0;
                    }

                    $result =   CustomerGoodsDataModel::insertAll($customerRectifyData);
                    if (!$result) {
                        // 回滚事务
                        Db::rollback();
                        $this->result([], "操作失败", 0);
                    }
                }


            }


        }
        elseif ($order_type == 9) {
            $rule['id|订单id'] = 'require';
            $rule['goods_data_id|产品id'] = 'require';
            $rule['sign_imgs|上传签收单'] = 'require';
            $rule['product_imgs|上传产品照片'] = 'require';
            $rule['service_level|服务等级1'] = 'require';
            //开始校验
            $this->validate($param, $rule);
            $data['rectify_content'] = json_encode($param['sign_imgs'], JSON_UNESCAPED_UNICODE);
            $data['product_imgs'] = json_encode($param['product_imgs'], JSON_UNESCAPED_UNICODE);
            $data['service_level'] = $param['service_level'];
            $up_data = ['order_status' => 10];

        }
        if (in_array($order_type, [1, 3, 4, 5, 6, 7, 8, 9]) && $data) {
            $result = $this->model->where('id', $param['id'])->update($data);
            if (!$result) {
                // 回滚事务
                Db::rollback();
                $this->result([], "操作失败11", 0);
            }

        }
        if (isset($up_data) && $up_data) {
            if (isset($param['id']) && $param['id']) {
                $goods_data_id = $this->model->where('id', $param['id'])->value('goods_data_id');
            } else {
                $goods_data_id = $param['goods_data_id'];
            }
            $result = CustomerGoodsDataModel::where('id', $goods_data_id)->update($up_data);
            if (!$result) {
                // 回滚事务
                Db::rollback();
                $this->result([], "操作失败", 0);
            }
        }


        Db::commit();
        //发送任务通知
        if(in_array($order_type,[0,1,3])){
            $this->taskModel->sendTaskInfo($dataTask['receive_admin_id'],$nodeProcess['process_name']);
        }
        $this->result([], '操作成功', 1);
    }

    //正单列表
    public function list()
    {
        $pageSize = $this->request->param('pageSize/d', 20); //每页多少条
        $pageNumber = $this->request->param('pageNumber/d') ?? 1; //当前页
        $order_type = $this->request->param('order_type', 0);
        $keyword = $this->request->param('keyword');
        $map = [];
        $map[] = ['customer_status', '=', 1];//正常状态下的可以
        if (!empty($keyword)) {
            $map[] = ['business_name|name|mobile|address|house_estate', 'like', '%' . $keyword . '%'];
        }


        $cutomerModel = new CustomerModel;
        $customer_ids = CustomerGoodsDataModel::where('contract_id', '<>', null)->column('customer_id');
        if (!$customer_ids) {
            $this->result([], '操作成功', 1);

        }
        $map[] = ['id', 'in', $customer_ids];//签过合同的客户

        $list = $cutomerModel->with(['customerGoodsData' => function ($query) use ($order_type) {
            //待下单
            if ($order_type == 0) {

                $query->where('type',null)->where('contract_id', '<>', null)->where('order_status', 0)->append(['order_status_text',]);
            }

            //待拆单
            if ($order_type == 1) {
                $query->where('type',null)->where('contract_id', '<>', null)->where('order_status', '>=', 1)->where('order_status', '<', 2)->append(['order_status_text',]);
            }
            //待复核
            if ($order_type == 2) {
                $query->where('type',null)->where('contract_id', '<>', null)->where('order_status', '>=', 2)->where('order_status', '<', 3)->append(['order_status_text',]);
            }
            //待核算
            if ($order_type == 3) {
                $query->where('type',null)->where('contract_id', '<>', null)->where('order_status', '>=', 3)->where('order_status', '<', 4)->append(['order_status_text',]);
            }
            //待回货
            if ($order_type == 4) {
                $query->where('type',null)->where('contract_id', '<>', null)->where('order_status', 4)->append(['order_status_text',]);
            }
            //待派工
            if ($order_type == 5) {
                $query->where('type',null)->where('contract_id', '<>', null)->where('order_status', 5)->append(['order_status_text',]);
            }
            //待安装
            if ($order_type == 6) {
                $query->where('type',null)->where('contract_id', '<>', null)->where('order_status', 6)->append(['order_status_text',]);
            }
            //安装中
            if ($order_type == 7) {
                $query->where('type',null)->where('contract_id', '<>', null)->where('order_status', 7)->append(['order_status_text',]);
            }
            //待验收
            if ($order_type == 8) {
                $query->where('type',null)->where('contract_id', '<>', null)->where('order_status', 8)->append(['order_status_text',]);
            }
            //待交付
            if ($order_type == 9) {
                $query->where('type',null)->where('contract_id', '<>', null)->where('order_status', 9)->append(['order_status_text',]);
            }
        }])
            ->where($map)
            ->withoutField('customer_file,customer_imgs')
             ->paginate(['list_rows'=> $pageSize, 'page' => $pageNumber]);

        $list = $this->model->_formatList($list);
        $this->result($list, '操作成功', 1);
    }

    //订单详情
    public function getInfo(Request $request)
    {
        $param = $request->param();
        //开始校验
        $this->validate($param, [
            'customer_id|客户id' => 'require',
            'goods_data_id|商品ID' => 'require',

        ]);
        $customer_info = CustomerModel::where('id', $param['customer_id'])
            ->field('id,business_name,name,mobile,province,city,dist,house_estate,address,channel_id,customer_pain_content,recommend_id')->find();

        if ($customer_info['recommend_id']) {
            $recommendInfo = RecommendModel::where('id', $customer_info['recommend_id'])->field('recommend_compay,recommend_name,recommend_mobile')->find();
            $customer_info['recommend_compay'] = $recommendInfo['recommend_compay'] ?? '';
            $customer_info['recommend_name'] = $recommendInfo['recommend_name'] ?? '';
            $customer_info['recommend_mobile'] = $recommendInfo['recommend_mobile'] ?? '';
        }
        $goods_info = CustomerGoodsDataModel::where('id', $param['goods_data_id'])->find();
        $customer_info['goods_name'] = $goods_info['goods_name'] ?? '';

        $data = [
            'customer_info' => $customer_info,

        ];
        if($goods_info['contract_id']){
            $contract_info = CustomerContractModel::where('id', $goods_info['contract_id'])->find();
            //合同信息
            if($contract_info){
                $contract_info['contract_imgs'] = json_decode($contract_info['contract_imgs'], true);
                $contract_info['drawing_imgs'] = json_decode($contract_info['drawing_imgs'], true);
                $contract_info['price_detail_imgs'] = json_decode($contract_info['price_detail_imgs'], true);
                $contract_info['sample_imgs'] = json_decode($contract_info['sample_imgs'], true);
                $contract_info['notice_imgs'] = json_decode($contract_info['notice_imgs'], true);
                $data['contract_info'] = $contract_info;
            }
        }



        //订单信息
        if ($goods_info['order_id']) {
            $order_info = OrderModel::where('id', $goods_info['order_id'])->find();
            $order_info['cad_imgs'] = json_decode($order_info['cad_imgs'], true);
            $order_info['install_notices'] = json_decode($order_info['install_notices'], true);
            $order_info['back_files'] = json_decode($order_info['back_files'], true);
            $order_info['cost_files'] = json_decode($order_info['cost_files'], true);
            $order_info['wage_infos'] = json_decode($order_info['wage_infos'], true);
            $order_info['diff_content'] = json_decode($order_info['diff_content'], true);
            $order_info['upload_imgs'] = json_decode($order_info['upload_imgs'], true);
            $order_info['legacy_infos'] = json_decode($order_info['legacy_infos'], true);
            $order_info['finish_install_imgs'] = json_decode($order_info['finish_install_imgs'], true);
            $order_info['finish_close_imgs'] = json_decode($order_info['finish_close_imgs'], true);
            $order_info['rectify_content'] = json_decode($order_info['rectify_content'], true);
            $order_info['sign_imgs'] = json_decode($order_info['sign_imgs'], true);
            $order_info['product_imgs'] = json_decode($order_info['product_imgs'], true);
            $data['order_info'] = $order_info;
            //$rectify_content = json_decode($order_info['rectify_content'], true);
//            $type_rectify_content = [];
//            if($rectify_content){
//                foreach($rectify_content as $v){
//                    if($v['question_way'] == 1){
//                        $type_rectify_content[1][] = ['question_way' => $v['question_way'], 'group_name' => $v['group_name'], 'file_url' => $v['file_url']];
//                    } elseif ($v['question_way'] == 2) {
//                        $type_rectify_content[2][] = ['question_way' => $v['question_way'], 'group_name' => $v['group_name'], 'file_url' => $v['file_url']];
//                    } elseif ($v['question_way'] == 3) {
//                        $type_rectify_content[3][] = ['question_way' => $v['question_way'], 'group_name' => $v['group_name'], 'file_url' => $v['file_url']];
//                    } elseif ($v['question_way'] == 4) {
//                        $type_rectify_content[4][] = ['question_way' => $v['question_way'], 'group_name' => $v['group_name'], 'file_url' => $v['file_url']];
//                    } elseif ($v['question_way'] == 5) {
//                        $type_rectify_content[5][] = ['question_way' => $v['question_way'], 'group_name' => $v['group_name'], 'file_url' => $v['file_url']];
//                    }elseif ($v['question_way'] == 6) {
//                        $type_rectify_content[6][] = ['question_way' => $v['question_way'], 'group_name' => $v['group_name'], 'file_url' => $v['file_url']];
//                    }
//                }
//            }
//
//            $data['rectifyData'] = $type_rectify_content;

        }
        if ($goods_info['rectify_content']) {
            $data['rectifyData'] =  json_decode($goods_info['rectify_content'], true);
        }
        if ($goods_info['result_content']) {
            $data['resultContent'] =  json_decode($goods_info['result_content'], true);
        }


//        //美容 安装 补材料
//        if(in_array($goods_info['type'],[1,2,3])){
//            $data['rectifyData'] = $goods_info['rectify_content'] ? json_decode($goods_info['rectify_content']) : [];
//        }
        $this->result($data, '操作成功', 1);
    }

    //获取登录人对客户及订单产品的权限-
    public function getShowRoleAuth()
    {
        $taskType = $this->request->param('task_type', 0);

        $type = $this->request->param('type', 0);//0 正单 1美容 2 安装 3补材料
        $customer_id = $this->request->param('customer_id', 0); //客户id
        $loginInfo = $this->loginInfo;

        $create_admin_id = CustomerAuthModel::where('customer_id', $customer_id)->where('role', 'create')->value('admin_id');
        $data = [];
        if ($loginInfo['id'] != $create_admin_id) {

            $role_ids = $this->role_ids;
            $customer_auth = RoleModel::where('id', $role_ids[0])->value('customer_auth');
            if ($customer_auth) {

                $data['customer_auth'] = RoleAuthModel::where('type_id', 1)->where('id', 'in', explode(',', $customer_auth))->field('id,name')->select();
            }

            else {
                $data['customer_auth'] = [];
            }


        } else {
            //对客户的操作权限
            $data['customer_auth'] = RoleAuthModel::where('type_id', 1)->where('id', 'in', [1, 2, 3, 4, 5, 7, 8, 10, 11])->field('id,name')->select();

        }


        if ($taskType == 0) {//待下单


            if(($type == 1 || $type == 2) && in_array(8, $this->role_ids)){
                //客户代表-尾单美容、安装
                $data['order_goods_auth'] = RoleAuthModel::where('type_id', 3)->where('id', 22)->field('id,name')->select();
            }
            elseif(in_array(6, $this->role_ids) && $type == 3)
            {
                //设计师-尾单补材料
                $data['order_goods_auth'] = RoleAuthModel::where('type_id', 3)->where('id', 22)->field('id,name')->select();
            } elseif(in_array(6, $this->role_ids) && $type == 0){
                //设计师-正单
                $data['order_goods_auth'] = RoleAuthModel::where('type_id', 3)->where('id', 22)->field('id,name')->select();
            }

            else {
                $data['order_goods_auth'] = [];
            }


        } elseif ($taskType == 1) {//待拆单
            //采购
            if (in_array(10, $this->role_ids)) {
                $data['order_goods_auth'] = RoleAuthModel::where('type_id', 3)->where('id', 23)->field('id,name')->select();
            } else {
                $data['order_goods_auth'] = [];
            }


        } elseif ($taskType == 2) {//待复核

            if (in_array(6, $this->role_ids) || in_array(8, $this->role_ids) || in_array(3, $this->role_ids) || in_array(5, $this->role_ids)) {
                $data['order_goods_auth'] = RoleAuthModel::where('type_id', 3)->where('id', 24)->field('id,name')->select();
            } else {
                $data['order_goods_auth'] = [];
            }


        } elseif ($taskType == 3) {//待核算

            if(($type == 1 || $type == 2) && in_array(11, $this->role_ids)){
                //尾单美容、安装
                $data['order_goods_auth'] = RoleAuthModel::where('type_id', 3)->where('id', 25)->field('id,name')->select();
            }elseif (in_array(10, $this->role_ids) || in_array(11, $this->role_ids) || in_array(2, $this->role_ids) || in_array(1, $this->role_ids)) {
                //正单、尾单补材料
                $data['order_goods_auth'] = RoleAuthModel::where('type_id', 3)->where('id', 25)->field('id,name')->select();
            } else {
                $data['order_goods_auth'] = [];
            }

        } elseif ($taskType == 4) {//待回货
            //采购
            if (in_array(10, $this->role_ids)) {
                $data['order_goods_auth'] = RoleAuthModel::where('type_id', 3)->where('id', 26)->field('id,name')->select();
            } else {
                $data['order_goods_auth'] = [];
            }
        } elseif ($taskType == 5) {//待派工
            //客户代表
            if (in_array(8, $this->role_ids)) {
                $data['order_goods_auth'] = RoleAuthModel::where('type_id', 3)->where('id', 27)->field('id,name')->select();
            } elseif (in_array(10, $this->role_ids)) {
                //采购
                $data['order_goods_auth'] = RoleAuthModel::where('type_id', 3)->where('id', 28)->field('id,name')->select();
            } else {
                $data['order_goods_auth'] = [];
            }
        } elseif ($taskType == 6) {//待安装
            //安装工
            if (in_array(14, $this->role_ids)) {
                $data['order_goods_auth'] = RoleAuthModel::where('type_id', 3)->where('id', 29)->field('id,name')->select();
            } elseif (in_array(10, $this->role_ids)) {
                $data['order_goods_auth'] = RoleAuthModel::where('type_id', 3)->where('id', 30)->field('id,name')->select();
            } elseif (in_array(8, $this->role_ids)) {
                $data['order_goods_auth'] = RoleAuthModel::where('type_id', 3)->where('id', 'in', [31, 32])->field('id,name')->select();
            } else {
                $data['order_goods_auth'] = [];
            }
        } elseif ($taskType == 7) {//安装中
            //安装工
            if (in_array(14, $this->role_ids)) {
                $data['order_goods_auth'] = RoleAuthModel::where('type_id', 3)->where('id', 'in', [33, 34])->field('id,name')->select();
            } else {
                $data['order_goods_auth'] = [];
            }

        } elseif ($taskType == 8) {//待验收
            if (in_array(16, $this->role_ids)) {
                $data['order_goods_auth'] = RoleAuthModel::where('type_id', 3)->where('id', 35)->field('id,name')->select();
            } else {
                $data['order_goods_auth'] = [];
            }
        } elseif ($taskType == 9) {//交付
            if (in_array(16, $this->role_ids)) {
                $data['order_goods_auth'] = RoleAuthModel::where('type_id', 3)->where('id', 36)->field('id,name')->select();
            } else {
                $data['order_goods_auth'] = [];
            }
        }


        $this->result($data, '操作成功', 1);
    }

    // 尾单列表
    public function weiList()
    {
        $pageSize = $this->request->param('pageSize/d', 20); //每页多少条
        $pageNumber = $this->request->param('pageNumber/d') ?? 1; //当前页
        $keyword = $this->request->param('keyword');
        $map = [];
        $map[] = ['customer_status', '=', 1];//正常状态下的可以
        if (!empty($keyword)) {
            $map[] = ['business_name|name|mobile|address|house_estate', 'like', '%' . $keyword . '%'];
        }


        $cutomerModel = new CustomerModel;
        $customer_ids = CustomerGoodsDataModel::where('contract_id', '<>', null)->column('customer_id');
        if (!$customer_ids) {
            $this->result([], '操作成功', 1);

        }
        $map[] = ['id', 'in', $customer_ids];//签过合同的客户
        $list = $cutomerModel->with(['customerGoodsData' => function ($query) {

            $query->where('type','<>', null)->append(['order_status_text',]);
                //->where('order_status', '<>', 8.1)


        }])
            ->where($map)
            ->withoutField('customer_file,customer_imgs')
             ->paginate(['list_rows'=> $pageSize, 'page' => $pageNumber]);
        $list = $this->model->_formatList($list);

        $this->result($list, '操作成功', 1);
    }

    //显示红点数量
    public function showRedOrderStatusNums(){
        $myCustomerIds = CustomerAuthModel::where('admin_id',$this->loginInfo['id'])->where('role','in',['create', 'relation'])->column('customer_id');

        $role_ids = $this->role_ids;
        $is_show = false;
        foreach ($role_ids as $v){
            if(in_array($v,[1,2,3,4])){
                $is_show = true;
            }
        }
        $map = [];
        if(!$is_show){

            $map[] = ['customer_id', 'in', $myCustomerIds];
        }
        $query = [];
        //待下单
        $query[1][] = ['order_status','=',0];
        //待拆单
        $query[2][] = ['order_status','>=',1];
        $query[2][] = ['order_status','<',2];
        //待复核
        $query[3][] = ['order_status','>=',2];
        $query[3][] = ['order_status','<',3];
        //待核算
        $query[4][] = ['order_status','>=',3];
        $query[4][] = ['order_status','<',4];
        //待回货
        $query[5][] = ['order_status','=',4];
        //待派工

        $query[6][] = ['order_status','=',5];
        //待安装
        $query[7][] = ['order_status','=',6];
        //安装中
        $query[8][] = ['order_status','=',7];

        //待验收
        $query[9][] = ['order_status','=',8];

        //待交付
        $query[10][] = ['order_status','=',9];
        //尾单数量
        $query[11][] = ['order_status','in',[0,1,3,4,5,6,7,8,9]];

        foreach ($query as $k=>$v){

            if($k <= 10){
                $data['total_' . $k] = CustomerGoodsDataModel::where($query[$k])->where($map)->where('type',null)->group('customer_id')->count();
            }
            else{

                $data['total_' . $k] = CustomerGoodsDataModel::where($query[$k])->where($map)->where('type','<>', null)->group('customer_id')->count();
            }

        }




        $this->result($data,'操作成功',1);
    }








}
